﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mimoza.Common;

namespace Mimoza.ObjectLayer
{
    public class PolicyRepository
    {
        private OL ol;
        public PolicyRepository(OL ol)
        {
            this.ol = ol;
            this.ol.DBLayer.DBPolicyRepository.OnObjectChanged += DBObjectChangedEventHandler;
        }

        public event EventHandler<ObjectLayer_ObjectChangedEventArgs> OnObjectChanged;
        private void RaiseOnObjectChanged(ObjectLayer_ObjectChangedEventArgs e)
        {
            EventHandler<ObjectLayer_ObjectChangedEventArgs> handler = OnObjectChanged;

            if (handler != null)
            {
                handler(this, e);
            }
        }
        void DBObjectChangedEventHandler(object sender, DBObjectChangedEventArgs e)
        {
            ObjectLayerEventType type = ObjectLayerEventType.ObjectInserted;
            Object obj;
            switch (e.EventType)
            {
                case DBEventType.ObjectInserted:
                    type = ObjectLayerEventType.ObjectInserted;
                    break;
                case DBEventType.ObjectUpdated:
                    type = ObjectLayerEventType.ObjectUpdated;
                    break;
                case DBEventType.ObjectDeleted:
                    type = ObjectLayerEventType.ObjectDeleted;
                    break;
            }

            obj = this.CreatePolicy(e.Object as PolicyRecord);
            ObjectLayer_ObjectChangedEventArgs args = new ObjectLayer_ObjectChangedEventArgs(obj, type);

            RaiseOnObjectChanged(args);
        }

        public Policy CreatePolicy()
        {
            return new Policy(ol);
        }
        public Policy CreatePolicy(Guid PolicyID)
        {
            PolicyRecord record = new PolicyRecord();
            record.ID = PolicyID;
            return new Policy(ol, record);
        }
        public Policy CreatePolicy(PolicyRecord record)
        {
            return new Policy(ol, record);
        }

        public Policy GetPolicyByID(Guid ID)
        {
            PolicyRecord record = ol.DBLayer.DBPolicyRepository.GetPolicy(ID);
            if (record == null) return null;
            return new Policy(ol, record);
        }

        public void Add(Policy policy)
        {
            ol.DBLayer.DBPolicyRepository.Insert(policy.Record);
        }
        public void Delete(Policy policy)
        {
            ol.DBLayer.DBPolicyRepository.Delete(policy.Record);
        }
        public void Update(Policy policy)
        {
            ol.DBLayer.DBPolicyRepository.Update(policy.Record);
        }
    }
}
